package com.cinco.blog.handler;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice   //拦截标有Controller的类
@Slf4j
public class ControllerExceptionHandler {

//    private final Logger logger= (Logger) LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)      //拦截Exception
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        log.error("Request URL : {},Exception : {}",request.getRequestURI(),e);

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURI());
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }
}
